<?php
namespace User\Controller;

use Zend\Mvc\MvcEvent;

use Zend\Form\Annotation\AnnotationBuilder;

use Zend\Mvc\Controller\AbstractActionController;
use User\Model\Entity\User;
use User\Form\RegisterForm;

class IndexController extends AbstractActionController{
	
	protected $userTable;
	protected $registerForm;

	public function getUserTable()
	{
		if (!$this->userTable) {
			$sm = $this->getServiceLocator();
			$this->userTable = $sm->get('User\Model\UserTable');
		}
		return $this->userTable;
	}
	
	public function getRegisterForm()
	{
		if(!$this->registerForm)
		{
			$user = new User();
			
			$this->registerForm = new RegisterForm();
			
			$this->registerForm->setInputFilter($user->getInputFilter());
		}
		
		return $this->registerForm;
	}
	
	public function indexAction()
	{
		$matches = $this->getEvent()->getRouteMatch();
		$page = $matches->getParam('page', 1);
	
		$resultSet = $this->getUserTable()->fetchAll();
		$resultSet->buffer();
		$resultSet->next();
	
		$paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\Iterator($resultSet));
	
		$paginator->setCurrentPageNumber($page);
		$paginator->setItemCountPerPage(40);
	
		return array('userArray' => $paginator);
	}
	
	public function detailAction()
	{
		$id = $this->params()->fromQuery('id');
		
		$user = $this->getUserTable()->getUser($id);
		
		return array('user' => $user);
	}

	public function addAction()
	{
		$form = $this->getRegisterForm();
		
		$request = $this->getRequest();
		
		if($request->isPost()) 
		{
			$form->setData($request->getPost());
			
			//The trict for not showing the error: Value is required and can't be empty
			$input = $form->getInputFilter();
			
			$e_filter = $input->get('email');
			$e_filter->setRequired(false);
			
			$dob_filter = $input->get('dob');
			$dob_filter->setRequired(false);
			
			if($form->isValid())
			{
				$user = new User();
				
				$user->exchangeArray($request->getPost());
				
				$this->getUserTable()->saveUser($user);
				
				$this->redirect()->toRoute('user/process', array('controller'=>'index', 'action'=>'index'));
			}
			
		}
		
		return array('registerForm' => $form,
				'messages'	=> $this->flashMessenger()->getMessages(),
				);
	}
}